package com.isunland.managesystem.base;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.widget.TextView;
import com.isunland.managesystem.adapter.ArrayDialogAdapter;
import java.util.ArrayList;

public abstract class BaseArrayDialogFragment<T> extends DialogFragment {
  public static final String EXTRA_VALUE =
      "com.isunland.intelligentFarmbyWJ.base.BaseArrayDialogFragment.EXTRA_VALUE";

  private ArrayDialogAdapter<T> mAdapter;
  private CallBack<T> mCallBack;

  protected abstract ArrayList<T> initData();

  public abstract void bindData(T object, TextView tv);

  @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) {
    mAdapter = new ArrayDialogAdapter<T>(initData(), getActivity()) {
      @Override public void initializeViews(T object, TextView tv) {
        bindData(object, tv);
      }
    };
    AlertDialog.Builder builderSingle = new AlertDialog.Builder(getActivity());
    builderSingle.setAdapter(mAdapter, new DialogInterface.OnClickListener() {

      @Override public void onClick(DialogInterface dialog, int which) {
        if (mCallBack != null) mCallBack.select(mAdapter.getItem(which));

        if (getTargetFragment() == null) return;
        Intent i = new Intent();
        i.putExtra(EXTRA_VALUE, (BaseModel) mAdapter.getItem(which));

        getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, i);
      }
    });
    return builderSingle.create();
  }

  public BaseArrayDialogFragment setCallBack(CallBack<T> callBack) {
    mCallBack = callBack;
    return this;
  }

  public interface CallBack<T> {
    void select(T base);
  }
}
